xquery version "1.0";

declare namespace util="http://exist-db.org/xquery/util";
declare namespace dc="http://purl.org/dc/elements/1.1/";
declare namespace request="http://exist-db.org/xquery/request";
declare namespace session="http://exist-db.org/xquery/session";

declare option exist:serialize "method=xhtml media-type=text/xml";


declare function local:orderSelection($track,$order) {
	if ($order = "name") 
		then $track/name
	else 
		if ($order = "comment-count") then $track/comment-count
		else 
			if ($order = "rating-count") then $track/rating-count
			else $track/name
		
	
};

element { "tracks" }{
	for $track in doc("Test1/Tracks.xml")//track
	let $order := request:get-parameter("order", ())
	let $name := request:get-parameter("name", ())
	where contains(fn:lower-case($track/name/text()), fn:lower-case($name))
	order by local:orderSelection($track,$order)
	return $track
}
			
